﻿package com.net.http;

import java.io.File;

import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.json.JSONArray;
import org.json.JSONObject;

import com.cn.mobileproject.data.GlobalValue;

public class HttpCom {
	
//	private static  HttpCom instance = new HttpCom();
	protected HttpClient httpclient;
	protected static String sid;
	public HttpCom(){
		httpclient = new HttpClient();
		if(GlobalValue.getInstance().getUser()!=null){
			httpclient.setSid(GlobalValue.getInstance().getUser().sid);
		}
	}
	
	public Response dopost(String url, byte[] b) throws HttpException{		
		return httpclient.httpRequest(formatUrl(url), b,null, HttpPost.METHOD_NAME);
	}
	
	public Response post(String url, JSONObject json) throws HttpException{		
		return httpclient.httpRequest(formatUrl(url), json, HttpPost.METHOD_NAME);
	}
	
	public Response post(String url, JSONArray array) throws HttpException{		
		return httpclient.httpRequestArray(formatUrl(url), array, HttpPost.METHOD_NAME);
	}
	
	public Response post(String url, File file) throws HttpException{		
		return httpclient.httpRequest(formatUrl(url), null, HttpPost.METHOD_NAME,file,null);
	}
	
	public Response post(String url,JSONObject json, File file) throws HttpException{		
		return httpclient.httpRequest(formatUrl(url), json, HttpPost.METHOD_NAME,file,null);
	}
	
	public Response get(String url ) throws HttpException{
		return httpclient.httpRequest(formatUrl(url), null, HttpGet.METHOD_NAME);
	}
	
	public Response put(String url , JSONObject json ) throws HttpException{
		return httpclient.httpRequest(formatUrl(url), json, HttpPut.METHOD_NAME);
	}

	public Response delete(String url)throws  HttpException{
		return httpclient.httpRequest(formatUrl(url), null, HttpDelete.METHOD_NAME);
	}
	
	
//    public String getSid(){
//        return this.sid;
//    } 
    
	protected String formatUrl(String url){
		
		String urltemp = url;
//		String sid = getSid();
		if(sid==null||"".equals(sid)||url == null) return url;		
		if(urltemp.contains("JSESSIONID")||urltemp.contains(sid)) return urltemp;
		else{
			if(urltemp.contains("?")){
				urltemp+="&JSESSIONID="+sid;
			}
			else{
				urltemp+="?JSESSIONID="+sid;
			}
		}
		return urltemp;
	}
}